﻿using UnityEngine;
using System.Collections;
using Common;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.Text;
using LitJson;
using System.Runtime.InteropServices;
using System;

 namespace tcpCommon
 {
     public class ClientTcp:OrdinarySingleton<ClientTcp>
{


    Socket clientSocket = null;

    Thread t = null;

    string ipAddress = "120.24.158.17";
    int ipPort = 4673;

    public void ConnectNet()
    {
        clientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

        clientSocket.Connect(new IPEndPoint(IPAddress.Parse(ipAddress), ipPort));

        t = new Thread(RecMessage);
        t.Start();
      //  RecMessage();
    }

    void RecMessage()
    {
        while (true)
        {
            byte[] data = new byte[1024];
            int length = clientSocket.Receive(data);
            string str = Encoding.UTF8.GetString(data,0,length);
            if (str != null && str != "")
                FpsShow.Instance.str = str;

//             Notification node = new Notification(str);
//             JSONNode ad = new JSONNode();
//             ad = JSON.Parse(str);
//             switch (int.Parse(ad["cmd"].ToString()))
//             {
//                 case (int)ClientPoll.pollEvent.Regist_Back_Event:
//                     NotficationCenter.Instance.PostNotificationEvent(ClientPoll.pollEvent.Regist_Back_Event.ToString(), node);             
//                     break;
//                 case (int)ClientPoll.pollEvent.Login_Back_Event:
//                     NotficationCenter.Instance.PostNotificationEvent(ClientPoll.pollEvent.Login_Back_Event.ToString(), node);
//                     break;
//                 default:
//                     break;
//             }
          
        }
    }

    public void shotThead()
    {
        clientSocket.Close();
        clientSocket = null;
        
        t.Abort();
        t = null;
    }

    public void SendMessage(object structobj)
    {
//         byte[] data = new byte[1024];
//         data = Encoding.UTF8.GetBytes(str);
        ProtocolPackage _package = new ProtocolPackage();
        TCP_Head tcpHead = default(TCP_Head);
        tcpHead.commandInfo.sMainCmdID = 111;
        tcpHead.commandInfo.sSubCmdID = 23;
        _package.CreatPackage(111, 23, 0, 0, structobj);
        byte[] data = _package.Getpackage();

        //加密数据
        //int wSendSize = EncryptBuffer(data, Marshal.SizeOf(tcpHead.GetType()), Marshal.SizeOf(structobj.GetType()));
        clientSocket.Send(data);
    }

//         //加密数据
//     int EncryptBuffer(byte[] pcbDataBuffer, int wDataSize, int wBufferSize)
//     {
//         TCP_Head tcpHead = default(TCP_Head);
//         TCP_Info tcp_info = default(TCP_Info);
//         int d_word = default(int);
// 	    //调整长度
//         int wEncryptSize = wDataSize - Marshal.SizeOf(tcpHead.GetType()), wSnapCount = 0;
//         if ((wEncryptSize % Marshal.SizeOf(d_word.GetType())) != 0)
// 	    {
// 		    wSnapCount=Marshal.SizeOf(d_word.GetType())-wEncryptSize%Marshal.SizeOf(d_word.GetType());
// 	    }
// 
// 	    //效验码与字节映射
// 	    byte cbCheckCode=0;
// 	    int i=0;
// 	    for (i=Marshal.SizeOf(tcp_info.GetType());i<wDataSize;i++)
// 	    {
// 		    cbCheckCode+=pcbDataBuffer[i];
// 	    }
// 
// 	    //填写信息头
// 	    TCP_Head pHead= (TCP_Head&)pcbDataBuffer;
//         pHead.tcpInfo.cbCheckCode = (byte)(~cbCheckCode + 1);
// 	    pHead.tcpInfo.sPacketSize=(short)wDataSize;
// 	    pHead.tcpInfo.cbDataKind=SOCKET_TCP_VER;
// 
// 	    //创建密钥
// 	    DWORD dwXorKey=m_dwSendXorKey;
// 	    if (m_dwSendPacketCount==0)
// 	    {
// 		    //生成第一次随机种子
// 		    GUID Guid;
// 		    CoCreateGuid(&Guid);
// 		    dwXorKey=GetTickCount()*GetTickCount();
// 		    dwXorKey^=Guid.Data1;
// 		    dwXorKey^=Guid.Data2;
// 		    dwXorKey^=Guid.Data3;
// 		    dwXorKey^=*((DWORD *)Guid.Data4);
// 		
// 		    //随机映射种子
// 		    dwXorKey=SeedRandMap((WORD)dwXorKey);
// 		    dwXorKey|=((DWORD)SeedRandMap((WORD)(dwXorKey>>16)))<<16;
// 		    dwXorKey^=g_dwPacketKey;
// 		    m_dwSendXorKey=dwXorKey;
// 		    m_dwRecvXorKey=dwXorKey;
// 	    }
// 
// 	    //加密数据
// 	    WORD * pwSeed=(WORD *)(pcbDataBuffer+sizeof(TCP_Info));
// 	    DWORD * pdwXor=(DWORD *)(pcbDataBuffer+sizeof(TCP_Info));
// 	    WORD wEncrypCount=(wEncryptSize+wSnapCount)/sizeof(DWORD);
// 	    for (i=0;i<wEncrypCount;i++)
// 	    {
// 		    *pdwXor++^=dwXorKey;
// 		    dwXorKey=SeedRandMap(*pwSeed++);
// 		    dwXorKey|=((DWORD)SeedRandMap(*pwSeed++))<<16;
// 		    dwXorKey^=g_dwPacketKey;
// 	    }
// 
// 	    //插入密钥
// 	    if (m_dwSendPacketCount==0)
// 	    {
// 		    MoveMemory(pcbDataBuffer+sizeof(TCP_Head)+sizeof(DWORD),pcbDataBuffer+sizeof(TCP_Head),wDataSize);
// 		    *((DWORD *)(pcbDataBuffer+sizeof(TCP_Head)))=m_dwSendXorKey;
// 		    pHead->TCPInfo.wPacketSize+=sizeof(DWORD);
// 		    wDataSize+=sizeof(DWORD);
// 	    }
// 
// 	    //设置变量
// 	    m_dwSendPacketCount++;
// 	    m_dwSendXorKey=dwXorKey;
// 
// 	    return wDataSize;
//     }

}
 }

